package com.magicalcoder.youyamvc.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.magicalcoder.youyamvc.app.adminuser.dto.AdminUserDto;
import com.magicalcoder.youyamvc.app.adminuser.dto.ModuleAndCategoryDto;
import com.magicalcoder.youyamvc.app.adminuser.service.AdminRoleModulePriorityService;
import com.magicalcoder.youyamvc.app.adminuser.util.AdminUserContextUtil;
import com.magicalcoder.youyamvc.app.logadminoperate.service.LogAdminOperateService;
import com.magicalcoder.youyamvc.app.model.LogAdminOperate;
import com.magicalcoder.youyamvc.core.cache.common.CacheUtil;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.spring.SpringContainer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginPagingController;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class AdminLoginInterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception arg3)
			throws Exception {


        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Object controller = handlerMethod.getBean();
        if(controller instanceof AdminLoginController){
            /*String methodName = handlerMethod.getMethod().getName();
            System.out.println(methodName);
            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();

            for(MethodParameter parameter:methodParameters){
                String parameterName = parameter.getParameterName();
                String parameterType = parameter.getParameterType().getTypeName();
                System.out.println(parameterType+" "+parameterName);
            }*/
        }

        /*HandlerMethod hm = (HandlerMethod)handler;
        Object hmBean = hm.getBean();
        if(hmBean instanceof AdminLoginController
                || hmBean instanceof AdminLoginPagingController) {//验证后台用户登录情况
            AdminUserDto adminUserDto = AdminUserContextUtil.getLoginUserDto(request);
            if(adminUserDto!=null){
                String url = request.getServletPath();
                //忽略查询功能
                if(request.getMethod().toLowerCase().equals("get")){
                    if(!url.contains("delete")&&!url.contains("update")&&!url.contains("save")
                            &&!url.contains("import")&&!url.contains("export")&&!url.contains("truncate")){
                        if(url.contains("type_ahead_search")||url.contains("detail")||url.contains("page")||url.contains("")){
                            return;
                        }
                    }
                }
                if(StringUtils.isNotBlank(request.getQueryString())){
                    url+="?"+request.getQueryString();
                }

                Map<String,Object> map = request.getParameterMap();
                Date now = new Date();
                LogAdminOperate log = new LogAdminOperate();
                log.setAdminUserId(adminUserDto.getId());
                log.setUserName(adminUserDto.getRealName());
                log.setCreateTime(now);
                log.setFormBody(JSON.toJSONString(map,true));
                log.setUrl(url);
                //还原历史记录 只支持带主键的表
                if(url.startsWith("/admin/")){
                    String[] arr =  url.split("/");
                    if(arr.length>2){
                        log.setTableName(arr[2]);
                    }
                    if(arr.length>3){
                        log.setOperateType(arr[3]);
                    }
                }
                //设置主键值magicalCoderDbPrimaryName是预先埋在页面的主键名称
                String magicalCoderDbPrimaryName = request.getParameter("magicalCoderDbPrimaryName");
                if(StringUtils.isNotBlank(magicalCoderDbPrimaryName)){
                    String primaryIdValue = request.getParameter(magicalCoderDbPrimaryName);
                    log.setPrimaryIdValue(primaryIdValue);
                }

                LogAdminOperateService logAdminOperateService = SpringContainer.getBean("logAdminOperateService", LogAdminOperateService.class);
                logAdminOperateService.insertLogAdminOperate(log);
            }
        }*/





	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
			Object handler) throws Exception {
        HandlerMethod hm = (HandlerMethod)handler;
        Object hmBean = hm.getBean();
        if(hmBean instanceof AdminLoginController
                || hmBean instanceof AdminLoginPagingController){//验证后台用户登录情况
            String sessionId = AdminUserContextUtil.getSessionKey(req);
            if(StringUtils.isBlank(sessionId)){
                RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/jsp/admin/login.jsp");
                dispatcher .forward(req, res);
                return false;
            }
            AdminUserDto adminUserDto = CacheUtil.get(sessionId);
            if(adminUserDto==null){//未登录
                RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/jsp/admin/login.jsp");
                dispatcher .forward(req, res);
                return false;
            }
            req.setAttribute("userLeftModules",adminUserDto.getUserLeftModules());
        }
        return true;//无需验证登录

    }

}
